Loops -(For va While Tsikllar)
Nazariya
Tsikllar dasturlashda takrorlanuvchi vazifalarni bajarish uchun ishlatiladi. Bu qismda For va While tsikllarni ko'rib chiqamiz:
- For loops - ma'lum miqdordagi takrorlash yoki ro'yxat ustida iteratsiya
- While loops - shart true bo'lgunga qadar takrorlash
For Loops
For Loop Turlari
- List iteration:
for item in list - Range loops:
for i in {start..end} - C-style loops:
for ((i=0; i<n; i++)) - Array iteration:
for element in "${array[@]}" - File globbing:
for file in *.txt
Amaliyot
#!/bin/bash
echo "============================================"
echo " FOR LOOPS DEMO"
echo "============================================"
# 1. BASIC FOR LOOPS
echo "=== 1. Asosiy For Tsikllar ==="
# Simple list iteration
echo "List iteratsiyasi:"
for fruit in olma banan anjir uzum; do
echo " 🍎 Meva: $fruit"
done
echo
# Range with numbers
echo "Raqamli diapazon:"
echo -n " Sonlar 1-10: "
for i in {1..10}; do
echo -n "$i "
done
echo -e "\n"
# Range with step
echo "Qadamli diapazon:"
echo -n " Juft sonlar 2-20: "
for i in {2..20..2}; do
echo -n "$i "
done
echo -e "\n"
# Array iteration
echo "Array iteratsiyasi:"
colors=("qizil" "ko'k" "yashil" "sariq")
for color in "${colors[@]}"; do
echo " 🎨 Rang: $color"
done
echo
# 2. C-STYLE FOR LOOPS
echo "=== 2. C-Style For Tsikllar ==="
# Basic C-style loop
echo "C-style tsikl:"
for ((i=1; i<=5; i++)); do
echo " Iteratsiya $i"
done
echo
# Multiplication table
echo "Ko'paytirish jadvali (5):"
for ((i=1; i<=10; i++)); do
result=$((5 * i))
printf " 5 x %2d = %2d\n" $i $result
done
echo
# Nested loops - pattern
echo "Yulduzcha naqshi:"
for ((i=1; i<=5; i++)); do
echo -n " "
for ((j=1; j<=i; j++)); do
echo -n "* "
done
echo
done
echo
# 3. FILE ITERATION
echo "=== 3. Fayl Iteratsiyasi ==="
# Create test environment
mkdir -p test_files/{docs,images,scripts}
touch test_files/docs/{doc1.txt,doc2.pdf,readme.md}
touch test_files/images/{photo1.jpg,photo2.png,logo.gif}
touch test_files/scripts/{backup.sh,deploy.py,config.json}
echo "Test muhiti yaratildi"
# Iterate through all files
echo "Barcha fayllar:"
for file in test_files/**/*; do
if [ -f "$file" ]; then
echo " 📄 $file"
fi
done
echo
# Iterate by file type
echo "Fayl turlari bo'yicha:"
echo " 📝 Matn fayllar:"
for file in test_files/**/*.{txt,md}; do
[ -f "$file" ] && echo " - $(basename "$file")"
done
echo " 🖼️ Rasm fayllar:"
for file in test_files/**/*.{jpg,png,gif}; do
[ -f "$file" ] && echo " - $(basename "$file")"
done
echo " 🔧 Script fayllar:"
for file in test_files/**/*.{sh,py}; do
[ -f "$file" ] && echo " - $(basename "$file")"
done
echo
# Cleanup
rm -rf test_files
# 4. ARRAY PROCESSING
echo "=== 4. Array Qayta Ishlash ==="
numbers=(5 12 8 3 15 7 20 1)
echo "Asl array: ${numbers[*]}"
# Find maximum
max=${numbers[0]}
for num in "${numbers[@]}"; do
if [ "$num" -gt "$max" ]; then
max=$num
fi
done
echo "Maksimal: $max"
# Find minimum
min=${numbers[0]}
for num in "${numbers[@]}"; do
if [ "$num" -lt "$min" ]; then
min=$num
fi
done
echo "Minimal: $min"
# Calculate sum
sum=0
for num in "${numbers[@]}"; do
sum=$((sum + num))
done
echo "Yig'indi: $sum"
echo "O'rtacha: $((sum / ${#numbers[@]}))"
echo
# String array processing
echo "String array qayta ishlash:"
names=("Ahmad Karimov" "Dilshod Umarov" "Madina Tosheva")
for i in "${!names[@]}"; do
name="${names[i]}"
first_name="${name% *}"
last_name="${name#* }"
echo " $((i+1)). $first_name $last_name"
echo " Ism: $first_name"
echo " Familiya: $last_name"
echo " Uzunlik: ${#name} belgi"
done
echo
# 5. PRACTICAL FOR EXAMPLES
echo "=== 5. Amaliy For Misollari ==="
# Progress bar simulation
echo "Progress bar simulatsiyasi:"
total=30
for ((i=0; i<=total; i++)); do
percent=$((i * 100 / total))
filled=$((i * 20 / total))
empty=$((20 - filled))
printf "\r Progress: ["
printf "%*s" $filled | tr ' ' '='
printf "%*s" $empty
printf "] %d%%" $percent
sleep 0.05
done
echo -e "\n"
# Password generator
echo "Parol generatori:"
chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*"
password_length=12
echo " Generatsiya qilingan parollar:"
for ((i=1; i<=3; i++)); do
password=""
for ((j=1; j<=password_length; j++)); do
random_index=$((RANDOM % ${#chars}))
password+="${chars:$random_index:1}"
done
echo " $i. $password"
done
echo
# System monitoring simulation
echo "Tizim monitoring simulatsiyasi:"
echo " Resurs ishlatilishi (3 ta o'lchov):"
for ((i=1; i<=3; i++)); do
cpu=$((RANDOM % 100))
memory=$((RANDOM % 100))
disk=$((RANDOM % 100))
timestamp=$(date '+%H:%M:%S')
printf " [%s] CPU: %2d%% | RAM: %2d%% | Disk: %2d%%\n" \
"$timestamp" $cpu $memory $disk
# Alert if high usage
if [ $cpu -gt 90 ] || [ $memory -gt 90 ] || [ $disk -gt 90 ]; then
echo " ⚠️ OGOHLANTIRISH: Yuqori resurs ishlatilishi!"
fi
sleep 1
done
echo
# File batch processor
echo "Fayl batch processor:"
# Create test files
mkdir -p batch_test
for i in {1..5}; do
echo "Content of file $i" > "batch_test/file_$i.txt"
done
echo " 📁 5 ta fayl yaratildi batch_test/ da"
processed_files=0
for file in batch_test/*.txt; do
if [ -f "$file" ]; then
filename=$(basename "$file")
echo " 📄 Processing: $filename"
# Simulate processing
sleep 0.5
# Add processed suffix
mv "$file" "${file%.txt}_processed.txt"
((processed_files++))
echo " ✅ Completed: ${filename%.txt}_processed.txt"
fi
done
echo " 📊 Jami qayta ishlandi: $processed_files ta fayl"
echo
# Cleanup
rm -rf batch_test
# Table generator
echo "Jadval generatori (Ko'paytirish jadvali 1-5):"
# Header
printf " %3s |" ""
for ((i=1; i<=5; i++)); do
printf "%4d" $i
done
echo
# Separator
printf " ----+"
for ((i=1; i<=5; i++)); do
printf "----"
done
echo
# Rows
for ((i=1; i<=5; i++)); do
printf " %3d |" $i
for ((j=1; j<=5; j++)); do
printf "%4d" $((i * j))
done
echo
done
echo
While Loops
While Loop Xususiyatlari
- Shart har iteratsiyada tekshiriladi
- Agar shart dastlab false bo'lsa, tsikl umuman ishlamaydi
- Infinite loop yaratish mumkin
- Input o'qish va foydalanuvchi interaksiyasi uchun ideal
Amaliyot
#!/bin/bash
echo "============================================"
echo " WHILE LOOPS DEMO"
echo "============================================"
# 1. BASIC WHILE LOOPS
echo "=== 1. Asosiy While Tsikllar ==="
# Simple counter
echo "Oddiy hisoblagich:"
counter=1
echo -n " Sonlar: "
while [ $counter -le 10 ]; do
echo -n "$counter "
((counter++))
done
echo -e "\n"
# Countdown timer
echo "Teskari hisoblagich:"
countdown=5
echo " Countdown boshlanmoqda..."
while [ $countdown -gt 0 ]; do
echo " $countdown"
sleep 1
((countdown--))
done
echo " 🚀 Ishga tushdi!"
echo
# User input validation
echo "Foydalanuvchi input validatsiyasi:"
valid_input=false
attempts=0
while [ "$valid_input" = false ] && [ $attempts -lt 3 ]; do
((attempts++))
read -p " 1-10 oralig'ida raqam kiriting (urinish $attempts/3): " user_number
if [[ "$user_number" =~ ^[0-9]+$ ]] && [ "$user_number" -ge 1 ] && [ "$user_number" -le 10 ]; then
echo " ✅ To'g'ri: $user_number"
valid_input=true
else
echo " ❌ Noto'g'ri! Iltimos, 1-10 oralig'ida raqam kiriting."
fi
done
if [ "$valid_input" = false ]; then
echo " 🔒 Maksimal urinishlar tugadi!"
fi
echo
# Random number guessing game
echo "Raqam topish o'yini:"
target_number=$((RANDOM % 10 + 1))
guess=0
attempts=0
max_attempts=5
echo " 🎯 1-10 oralig'idagi raqamni toping!"
while [ $guess -ne $target_number ] && [ $attempts -lt $max_attempts ]; do
((attempts++))
read -p " Taxminingiz (urinish $attempts/$max_attempts): " guess
if ! [[ "$guess" =~ ^[0-9]+$ ]]; then
echo " ❌ Iltimos, raqam kiriting!"
((attempts--)) # Don't count invalid input
continue
fi
if [ $guess -lt $target_number ]; then
echo " 📈 Kattaroq raqam!"
elif [ $guess -gt $target_number ]; then
echo " 📉 Kichikroq raqam!"
else
echo " 🎉 To'g'ri! $attempts urinishda topdingiz!"
fi
done
if [ $guess -ne $target_number ]; then
echo " 💀 Yutqazdingiz! Raqam $target_number edi."
fi
echo
# 2. FILE PROCESSING WITH WHILE
echo "=== 2. While bilan Fayl Qayta Ishlash ==="
# Create sample data files
cat > users.txt << 'EOF'
Ahmad:25:Toshkent:Developer
Dilshod:30:Samarqand:Designer
Madina:28:Buxoro:Manager
Jasur:35:Namangan:Analyst
Zarina:27:Farg'ona:Tester
EOF
cat > sales.csv << 'EOF'
Date,Product,Amount,Customer
2024-01-15,Laptop,1200,Ahmad
2024-01-16,Mouse,25,Dilshod
2024-01-17,Keyboard,75,Madina
2024-01-18,Monitor,300,Jasur
2024-01-19,Laptop,1200,Zarina
EOF
echo "Test fayllar yaratildi: users.txt va sales.csv"
echo
# Process user data
echo "Foydalanuvchi ma'lumotlarini qayta ishlash:"
user_count=0
total_age=0
while IFS=':' read -r name age city job; do
((user_count++))
total_age=$((total_age + age))
echo " 👤 $name ($age yosh) - $job, $city"
done < users.txt
average_age=$((total_age / user_count))
echo
echo " 📊 Statistika:"
echo " Jami foydalanuvchilar: $user_count"
echo " O'rtacha yosh: $average_age"
echo
# Process CSV data
echo "CSV ma'lumotlarini qayta ishlash:"
line_number=0
total_sales=0
declare -A product_sales
while IFS=',' read -r date product amount customer; do
((line_number++))
# Skip header
if [ $line_number -eq 1 ]; then
echo " 📋 Header: $date, $product, $amount, $customer"
continue
fi
echo " 💰 $date: $customer bought $product for \$${amount}"
total_sales=$((total_sales + amount))
# Track product sales
if [[ -n "${product_sales[$product]}" ]]; then
product_sales[$product]=$((product_sales[$product] + amount))
else
product_sales[$product]=$amount
fi
done < sales.csv
echo
echo " 📊 Sotuv statistikasi:"
echo " Jami sotuv: \$${total_sales}"
echo " Mahsulot bo'yicha:"
for product in "${!product_sales[@]}"; do
echo " $product: \$${product_sales[$product]}"
done
echo
# Cleanup
rm -f users.txt sales.csv
# 3. INTERACTIVE WHILE LOOPS
echo "=== 3. Interaktiv While Tsikllar ==="
# Simple calculator
echo "Oddiy kalkulyator (chiqish uchun 'q' yozing):"
calc_count=0
while [ $calc_count -lt 3 ]; do # Limited for demo
((calc_count++))
echo
read -p " Birinchi raqamni kiriting (yoki 'q'): " first_num
if [ "$first_num" = "q" ]; then
echo " 👋 Kalkulyator yopildi!"
break
fi
if ! [[ "$first_num" =~ ^-?[0-9]+([.][0-9]+)?$ ]]; then
echo " ❌ Noto'g'ri raqam format!"
continue
fi
read -p " Operator kiriting (+, -, *, /): " operator
read -p " Ikkinchi raqamni kiriting: " second_num
if ! [[ "$second_num" =~ ^-?[0-9]+([.][0-9]+)?$ ]]; then
echo " ❌ Noto'g'ri raqam format!"
continue
fi
case "$operator" in
"+")
result=$((first_num + second_num))
echo " ✅ Natija: $first_num + $second_num = $result"
;;
"-")
result=$((first_num - second_num))
echo " ✅ Natija: $first_num - $second_num = $result"
;;
"*")
result=$((first_num * second_num))
echo " ✅ Natija: $first_num * $second_num = $result"
;;
"/")
if [ "$second_num" = "0" ]; then
echo " ❌ Nolga bo'lish mumkin emas!"
else
result=$((first_num / second_num))
echo " ✅ Natija: $first_num / $second_num = $result"
fi
;;
*)
echo " ❌ Noma'lum operator: $operator"
;;
esac
done
echo
# Menu system
echo "Menu tizimi:"
menu_active=true
menu_count=0
while [ "$menu_active" = true ] && [ $menu_count -lt 3 ]; do
((menu_count++))
echo
echo " ╔══════════════════════════════════════╗"
echo " ║ ASOSIY MENU ║"
echo " ╠══════════════════════════════════════╣"
echo " ║ 1. Tizim ma'lumotlari ║"
echo " ║ 2. Disk joy ko'rsatish ║"
echo " ║ 3. Sana va vaqt ║"
echo " ║ 4. Chiqish ║"
echo " ╚══════════════════════════════════════╝"
echo
read -p " Tanlovingizni kiriting (1-4): " menu_choice
case $menu_choice in
1)
echo " 📊 Tizim ma'lumotlari:"
echo " OS: $(uname -o)"
echo " Kernel: $(uname -r)"
echo " Arxitektura: $(uname -m)"
;;
2)
echo " 💾 Disk joy:"
df -h | head -3
;;
3)
echo " 🕐 Sana va vaqt:"
echo " $(date)"
;;
4)
echo " 👋 Xayr!"
menu_active=false
;;
*)
echo " ❌ Noto'g'ri tanlov: $menu_choice"
;;
esac
if [ "$menu_active" = true ]; then
read -p " Davom etish uchun Enter bosing..."
fi
done
echo
# 4. SYSTEM MONITORING WITH WHILE
echo "=== 4. Tizim Monitoring with While ==="
# Resource monitor
echo "Resurs monitorial (3 ta o'lchov, har 2 soniyada):"
count=0
max_count=3
while [ $count -lt $max_count ]; do
((count++))
timestamp=$(date '+%H:%M:%S')
# Simulate system metrics
cpu_usage=$((RANDOM % 100))
memory_usage=$((RANDOM % 100))
disk_usage=$((RANDOM % 100))
network_io=$((RANDOM % 1000))
printf " [%s] " "$timestamp"
printf "CPU: %2d%% | " $cpu_usage
printf "RAM: %2d%% | " $memory_usage
printf "Disk: %2d%% | " $disk_usage
printf "Network: %3d KB/s" $network_io
echo
# Check for alerts
alerts=()
[ $cpu_usage -gt 90 ] && alerts+=("CPU yuqori")
[ $memory_usage -gt 85 ] && alerts+=("RAM yuqori")
[ $disk_usage -gt 95 ] && alerts+=("Disk to'la")
if [ ${#alerts[@]} -gt 0 ]; then
echo " 🚨 ALERT: ${alerts[*]}"
fi
# Don't sleep on last iteration
if [ $count -lt $max_count ]; then
sleep 2
fi
done
echo
# Log watcher simulation
echo "Log watcher simulatsiyasi:"
# Create a growing log file
echo "Starting application..." > app.log
log_lines=0
max_lines=5
echo " 📝 Log fayl kuzatilmoqda..."
while [ $log_lines -lt $max_lines ]; do
# Simulate new log entries
timestamp=$(date '+%H:%M:%S')
log_entries=("User connected" "Processing request" "Database query" "Sending response" "User disconnected")
new_entry="${timestamp} INFO ${log_entries[$log_lines]}"
echo "$new_entry" >> app.log
echo " 📄 Yangi log: $new_entry"
((log_lines++))
sleep 1
done
echo " ✅ Log monitoring tugallandi"
echo
# Cleanup
rm -f app.log
echo "============================================"
echo " FOR VA WHILE LOOPS TUGADI"
echo "============================================"